package server

import (
	"database/sql"
	"log"
	"net/http"

	_ "github.com/go-sql-driver/mysql"
	"github.com/redis/go-redis/v9"
	"github.com/uptrace/bun"
	"github.com/uptrace/bun/dialect/mysqldialect"
	"github.com/uptrace/bun/extra/bundebug"

	"ctfo-platform-go/config"
)

var (
	db  *bun.DB
	rdb *redis.Client
)

func Init(conf config.Config) error {

	sqldb, err := sql.Open("mysql", conf.DataSource.Name)
	if err != nil {
		return err
	}

	db = bun.NewDB(sqldb, mysqldialect.New())
	db.AddQueryHook(bundebug.NewQueryHook(bundebug.WithVerbose(true)))

	rdb = redis.NewClient(&redis.Options{
		Addr:     conf.Redis.Addr,
		Password: conf.Redis.Password, // no password set
		DB:       conf.Redis.DB,       // use default DB
	})

	return nil
}

func Start(addr string) {
	handler := newRouter()
	log.Printf("Listening and serving HTTP on %s\n", addr)

	err := http.ListenAndServe(addr, handler)
	if err != nil {
		log.Fatalf("http start failed: %v", err)
	}

}
